<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|consolas:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android,Project," />





  <link rel="alternate" href="/atom.xml" title="🐕 @Leeifme" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言:前几天，都在准备软考，果然大学都是让人变懒的地方， 感觉这种刷题就能过的题目，要是放在两年前的我，也不一定能过， 反正最后感觉还不如拿报名费和学妹去吃火锅💔 心痛，没有学妹💥  虽然是基础封装，但也证明了是底层封装，越是底层，越要逻辑清晰，条理严谨 这样才便于之后维护以及重构………   封装ListView第一层封装 adapter —&amp;gt; MyBaseAdapter.java">
<meta name="keywords" content="Android,Project">
<meta property="og:type" content="article">
<meta property="og:title" content="应用市场（二）——基础封装">
<meta property="og:url" content="http://www.leeif.me/coding/android/project/ApplicationMarket/应用市场(二)-基础封装/index.html">
<meta property="og:site_name" content="🐕 @Leeifme">
<meta property="og:description" content="前言:前几天，都在准备软考，果然大学都是让人变懒的地方， 感觉这种刷题就能过的题目，要是放在两年前的我，也不一定能过， 反正最后感觉还不如拿报名费和学妹去吃火锅💔 心痛，没有学妹💥  虽然是基础封装，但也证明了是底层封装，越是底层，越要逻辑清晰，条理严谨 这样才便于之后维护以及重构………   封装ListView第一层封装 adapter —&amp;gt; MyBaseAdapter.java">
<meta property="og:image" content="http://oce2u4egr.bkt.clouddn.com/78805a221a988e79ef3f42d7c5bfd418.gif">
<meta property="og:image" content="http://oce2u4egr.bkt.clouddn.com/ApplicationMarket-Listview.gif">
<meta property="og:image" content="http://oce2u4egr.bkt.clouddn.com/ApplicationMarket-Protocol.gif">
<meta property="og:updated_time" content="2017-07-02T09:56:35.614Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="应用市场（二）——基础封装">
<meta name="twitter:description" content="前言:前几天，都在准备软考，果然大学都是让人变懒的地方， 感觉这种刷题就能过的题目，要是放在两年前的我，也不一定能过， 反正最后感觉还不如拿报名费和学妹去吃火锅💔 心痛，没有学妹💥  虽然是基础封装，但也证明了是底层封装，越是底层，越要逻辑清晰，条理严谨 这样才便于之后维护以及重构………   封装ListView第一层封装 adapter —&amp;gt; MyBaseAdapter.java">
<meta name="twitter:image" content="http://oce2u4egr.bkt.clouddn.com/78805a221a988e79ef3f42d7c5bfd418.gif">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: undefined,
      author: 'Author'
    }
  };
</script>




  <link rel="canonical" href="http://www.leeif.me/coding/android/project/ApplicationMarket/应用市场(二)-基础封装/"/>

  <title> 应用市场（二）——基础封装 | 🐕 @Leeifme </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>
    
    <header id="header_post" class="header" itemscope itemtype="http://schema.org/WPHeader" style="background-image: url('/images/4.jpg');">
      <div class="header-inner-post"><a class="site-home" href="/">🐕 @Leeifme</a>

<div class="site-meta custom-logo">
  
  
  
    <div class="site-meta-headline">
      <a>
        <img class="custom-logo-image" src="/images/logo.png" style="width: 80px"
             alt="🐕 @Leeifme"/>
      </a>
    </div>
  

  
  
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        
        
           <li class="menu-item menu-item-about">
             <a href="/about" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
               
               
               about
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-movie">
             <a href="/movie" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-superscript"></i> <br />
               
               
               movie
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-coding">
             <a href="/categories/coding" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-cogs"></i> <br />
               
               
               coding
             </a>
           </li>
        
      
        
        
        
           <li class="menu-item menu-item-archives">
             <a href="/archives" rel="section">
               
                 <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
               
               
               archives
             </a>
           </li>
        
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <input type="text" id="local-search-input">
 <span class="search-icon fa fa-search"></span>
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
      <div class="header-post"> 
  <div class="post-header">
      <div class="tags">
      
        <a href="/tags/Android/" rel="tag" title="Android">Android</a>
      
        <a href="/tags/Project/" rel="tag" title="Project">Project</a>
      
      </div>
      <h1>应用市场（二）——基础封装</h1>
      <h2 class="subtitle"></h2>
      <div class="post-time">
        <span class="post-meta-item-text">Posted on </span>
        <time itemprop="dateCreated" datetime="2017-03-10T11:30:05+08:00" content="2017-03-10" title="2017-03-10 11:30:05">
          2017-03-10
        </time>
      </div>
  </div>
 </div>
    </header>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                应用市场（二）——基础封装
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2017-03-10T11:30:05+08:00" content="2017-03-10">
              2017-03-10
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/coding/" itemprop="url" rel="index">
                    <span itemprop="name">coding</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/coding/android/" itemprop="url" rel="index">
                    <span itemprop="name">android</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/coding/android/project/" itemprop="url" rel="index">
                    <span itemprop="name">project</span>
                  </a>
                </span>

                
                

              
            </span>
          

          <!-- 
            
           -->

          

          
          
             <span id="/coding/android/project/ApplicationMarket/应用市场(二)-基础封装/" class="leancloud_visitors" data-flag-title="应用市场（二）——基础封装">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv"><i class="fa fa-eye"> </i>
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <link rel="stylesheet" type="text/css" href="/assets/css/DPlayer.min.css"><script src="/assets/js/DPlayer.min.js"> </script><script src="/assets/js/APlayer.min.js"> </script><blockquote>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言:"></a>前言:</h2><p>前几天，都在准备软考，果然大学都是让人变懒的地方，</p>
<p>感觉这种刷题就能过的题目，要是放在两年前的我，也不一定能过，</p>
<p>反正最后感觉还不如拿报名费和学妹去吃火锅💔</p>
<p>心痛，没有学妹💥</p>
<hr>
<p>虽然是基础封装，但也证明了是底层封装，越是底层，越要逻辑清晰，条理严谨</p>
<p>这样才便于之后维护以及重构………</p>
</blockquote>
<p><img src="http://oce2u4egr.bkt.clouddn.com/78805a221a988e79ef3f42d7c5bfd418.gif"></p>
<h1 id="封装ListView"><a href="#封装ListView" class="headerlink" title="封装ListView"></a>封装ListView</h1><h2 id="第一层封装"><a href="#第一层封装" class="headerlink" title="第一层封装"></a>第一层封装</h2><blockquote>
<p>adapter —&gt; <code>MyBaseAdapter.java</code></p>
</blockquote>
<a id="more"></a>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBaseAdapter</span>&lt;<span class="title">T</span>&gt; <span class="keyword">extends</span> <span class="title">BaseAdapter</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> ArrayList&lt;T&gt; data <span class="comment">//用泛型;</span></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MyBaseAdapter</span><span class="params">(ArrayList&lt;T&gt; data)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.data = data;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getCount</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> data.size();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getItem</span><span class="params">(<span class="keyword">int</span> position)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> data.get(position);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getItemId</span><span class="params">(<span class="keyword">int</span> position)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> position;</div><div class="line">    &#125;</div><div class="line">   <span class="function"><span class="keyword">public</span> View <span class="title">getView</span><span class="params">(<span class="keyword">int</span> position, View convertView, ViewGroup parent)</span>     </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>在<code>HomeFragment</code>中，<code>HomeAdapter</code>继承<code>MyBaseAdapter</code>，并实现父类的构造方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">HomeAdapter</span> <span class="keyword">extends</span> <span class="title">MyBaseAdapter</span>&lt;<span class="title">String</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="title">HomeAdapter</span><span class="params">(ArrayList&lt;String&gt; data)</span> </span>&#123; <span class="comment">//String类型</span></div><div class="line">            <span class="keyword">super</span>(data);</div><div class="line">        &#125;</div></pre></td></tr></table></figure>
<h2 id="第二层封装"><a href="#第二层封装" class="headerlink" title="第二层封装"></a>第二层封装</h2><blockquote>
<p>对<code>getView</code>进行封装</p>
<p>holder —&gt; <code>BaseHolder.java</code></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseHolder</span>&lt;<span class="title">T</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> View mRootView;<span class="comment">// 一个item的根布局</span></div><div class="line"></div><div class="line">    <span class="keyword">private</span> T data;</div><div class="line"></div><div class="line">    <span class="comment">//当new这个对象时, 就会加载布局, 初始化控件,设置tag</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BaseHolder</span><span class="params">()</span> </span>&#123;</div><div class="line">        mRootView = initView();</div><div class="line">        <span class="comment">// 3. 打一个标记tag</span></div><div class="line">        mRootView.setTag(<span class="keyword">this</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 1. 加载布局文件</span></div><div class="line">    <span class="comment">// 2. 初始化控件 findViewById</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> View <span class="title">initView</span><span class="params">()</span></span>;</div><div class="line"></div><div class="line">    <span class="comment">// 返回item的布局对象</span></div><div class="line">    <span class="function"><span class="keyword">public</span> View <span class="title">getRootView</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> mRootView;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 设置当前item的数据</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setData</span><span class="params">(T data)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.data = data;</div><div class="line">        refreshView(data);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 获取当前item的数据</span></div><div class="line">    <span class="function"><span class="keyword">public</span> T <span class="title">getData</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> data;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 4. 根据数据来刷新界面</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">refreshView</span><span class="params">(T data)</span></span>;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>由于<code>MyBaseAdapter</code> 和<code>BaseHolder</code>同属父类，实现方法简单</p>
<p>在<code>MyBaseAdapter</code>实现<code>getView</code>封装</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> View <span class="title">getView</span><span class="params">(<span class="keyword">int</span> position, View convertView, ViewGroup parent)</span> </span>&#123;</div><div class="line">        BaseHolder holder;</div><div class="line">        <span class="keyword">if</span> (convertView == <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="comment">// 1. 加载布局文件</span></div><div class="line">            <span class="comment">// 2. 初始化控件 findViewById</span></div><div class="line">            <span class="comment">// 3. 打一个标记tag</span></div><div class="line">            holder = getHolder();<span class="comment">// 子类返回具体对象</span></div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            holder = (BaseHolder) convertView.getTag();</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 4. 根据数据来刷新界面</span></div><div class="line">        holder.setData(getItem(position));</div><div class="line"></div><div class="line">        <span class="keyword">return</span> holder.getRootView();</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<p>在<code>HomeFragment</code>中，<code>getHodler()</code>必须返回一个具体的Holder对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> BaseHolder&lt;String&gt; <span class="title">getHolder</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> HomeHolder();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>所以新建<code>HomeHoider.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HomeHolder</span> <span class="keyword">extends</span> <span class="title">BaseHolder</span>&lt;<span class="title">AppInfo</span>&gt; </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> TextView tvContent;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> View <span class="title">initView</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="comment">// 1. 加载布局</span></div><div class="line">        View view = UIUtils.inflate(R.layout.list_item_home);</div><div class="line">        <span class="comment">// 2. 初始化控件</span></div><div class="line">        tvContent = (TextView) view.findViewById(R.id.tv_content);</div><div class="line">        <span class="keyword">return</span> view;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refreshView</span><span class="params">(String data)</span> </span>&#123;</div><div class="line">        tvContent.setText(data);</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<h2 id="ListView增加加载更多布局"><a href="#ListView增加加载更多布局" class="headerlink" title="ListView增加加载更多布局"></a>ListView增加加载更多布局</h2><blockquote>
<p>增加布局类型</p>
<p> <code>MyBaseAdapter.java</code></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//注意: 此处必须要从0开始写，底层很多Adapter是集合数组</span></div><div class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> TYPE_NORMAL = <span class="number">0</span>;<span class="comment">// 正常布局类型</span></div><div class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> TYPE_MORE = <span class="number">1</span>;<span class="comment">// 加载更多类型</span></div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 返回布局类型个数</span></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getViewTypeCount</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="number">2</span>;<span class="comment">// 返回两种类型,普通布局+加载更多布局</span></div><div class="line">&#125;</div><div class="line"><span class="comment">// 返回当前位置应该展示那种布局类型</span></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getItemViewType</span><span class="params">(<span class="keyword">int</span> position)</span> </span>&#123;</div><div class="line">    <span class="keyword">if</span> (position == getCount() - <span class="number">1</span>) &#123;<span class="comment">// 最后一个</span></div><div class="line">        <span class="keyword">return</span> TYPE_MORE;</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        <span class="keyword">return</span> getInnerType();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p><code>MoreHolder.java</code>根据状态加载不同的状态</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 1. 可以加载更多</span></div><div class="line"><span class="comment">// 2. 加载更多失败</span></div><div class="line"><span class="comment">// 3. 没有更多数据</span></div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> STATE_MORE_MORE = <span class="number">1</span>;</div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> STATE_MORE_ERROR = <span class="number">2</span>;</div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> STATE_MORE_NONE = <span class="number">3</span>;</div></pre></td></tr></table></figure>
<blockquote>
<p>加载更多数据逻辑</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 加载更多数据</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">loadMore</span><span class="params">(<span class="keyword">final</span> MoreHolder holder)</span> </span>&#123;</div><div class="line">    <span class="keyword">if</span> (!isLoadMore) &#123;</div><div class="line">        isLoadMore = <span class="keyword">true</span>;</div><div class="line">        <span class="keyword">new</span> Thread() &#123;</div><div class="line">            <span class="meta">@Override</span></div><div class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">                <span class="keyword">final</span> ArrayList&lt;T&gt; moreData = onLoadMore();</div><div class="line">                UIUtils.runOnUIThread(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">                    <span class="meta">@Override</span></div><div class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">                        <span class="keyword">if</span> (moreData != <span class="keyword">null</span>) &#123;</div><div class="line">                            <span class="comment">// 每一页有20条数据, 如果返回的数据小于20条, 就认为到了最后一页了</span></div><div class="line">                            <span class="keyword">if</span> (moreData.size() &lt; <span class="number">20</span>) &#123;</div><div class="line">                                holder.setData(MoreHolder.STATE_MORE_NONE);</div><div class="line">                                Toast.makeText(UIUtils.getContext(),</div><div class="line">                                        <span class="string">"没有更多数据了"</span>, Toast.LENGTH_SHORT)</div><div class="line">                                        .show();</div><div class="line">                            &#125; <span class="keyword">else</span> &#123;</div><div class="line">                                <span class="comment">// 还有更多数据</span></div><div class="line">                                holder.setData(MoreHolder.STATE_MORE_MORE);</div><div class="line">                            &#125;</div><div class="line">                            <span class="comment">// 将更多数据追加到当前集合中</span></div><div class="line">                            data.addAll(moreData);</div><div class="line">                            <span class="comment">// 刷新界面</span></div><div class="line">                            MyBaseAdapter.<span class="keyword">this</span>.notifyDataSetChanged();</div><div class="line">                        &#125; <span class="keyword">else</span> &#123;</div><div class="line">                            <span class="comment">// 加载更多失败</span></div><div class="line">                            holder.setData(MoreHolder.STATE_MORE_ERROR);</div><div class="line">                        &#125;</div><div class="line">                        isLoadMore = <span class="keyword">false</span>;</div><div class="line">                    &#125;</div><div class="line">                &#125;);</div><div class="line">            &#125;</div><div class="line">        &#125;.start();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里对ListView加载更多的布局封装，操作较多，建议Clone源码对照看。</p>
<blockquote>
<h1 id="封装ListView加载测试数据，演示效果"><a href="#封装ListView加载测试数据，演示效果" class="headerlink" title="封装ListView加载测试数据，演示效果"></a>封装ListView加载测试数据，演示效果</h1><p><img src="http://oce2u4egr.bkt.clouddn.com/ApplicationMarket-Listview.gif"></p>
</blockquote>
<h1 id="网络数据请求封装"><a href="#网络数据请求封装" class="headerlink" title="网络数据请求封装"></a>网络数据请求封装</h1><h2 id="导入http工具包及工具类"><a href="#导入http工具包及工具类" class="headerlink" title="导入http工具包及工具类"></a>导入http工具包及工具类</h2><blockquote>
<ul>
<li>http<ul>
<li>HttpClientFactory.java</li>
<li>HttpHelper.java</li>
</ul>
</li>
<li>utils<ul>
<li>IOUtils.java</li>
<li>LogUtils.java</li>
<li>String.java</li>
</ul>
</li>
</ul>
</blockquote>
<h2 id="封装访问网络的基类"><a href="#封装访问网络的基类" class="headerlink" title="封装访问网络的基类"></a>封装访问网络的基类</h2><p><code>protocol —&gt; BaseProtocol.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// index表示的是从哪个位置开始返回20条数据, 用于分页</span></div><div class="line"><span class="function"><span class="keyword">public</span> T <span class="title">getData</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</div><div class="line">    <span class="comment">// 先判断是否有缓存, 有的话就加载缓存</span></div><div class="line">    String result = getCache(index);</div><div class="line">    <span class="keyword">if</span> (StringUtils.isEmpty(result)) &#123;<span class="comment">// 如果没有缓存,或者缓存失效</span></div><div class="line">        <span class="comment">// 请求服务器</span></div><div class="line">        result = getDataFromServer(index);</div><div class="line">    &#125;</div><div class="line">    <span class="comment">// 开始解析</span></div><div class="line">    <span class="keyword">if</span> (result != <span class="keyword">null</span>) &#123;</div><div class="line">        T data = parseData(result);</div><div class="line">        <span class="keyword">return</span> data;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">&#125;</div><div class="line"><span class="comment">// 从网络获取数据</span></div><div class="line"><span class="comment">// index表示的是从哪个位置开始返回20条数据, 用于分页</span></div><div class="line"><span class="function"><span class="keyword">private</span> String <span class="title">getDataFromServer</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</div><div class="line">    HttpResult httpResult = HttpHelper.get(HttpHelper.URL + getKey()</div><div class="line">            + <span class="string">"?index="</span> + index + getParams());</div><div class="line">    <span class="keyword">if</span> (httpResult != <span class="keyword">null</span>) &#123;</div><div class="line">        String result = httpResult.getString();</div><div class="line">        System.out.println(<span class="string">"访问结果:"</span> + result);</div><div class="line">        <span class="comment">// 写缓存</span></div><div class="line">        <span class="keyword">if</span> (!StringUtils.isEmpty(result)) &#123;</div><div class="line">            setCache(index, result);</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> result;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">&#125;</div><div class="line"><span class="comment">// 获取网络链接关键词, 子类必须实现</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> String <span class="title">getKey</span><span class="params">()</span></span>;</div><div class="line"><span class="comment">// 获取网络链接参数, 子类必须实现</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> String <span class="title">getParams</span><span class="params">()</span></span>;</div></pre></td></tr></table></figure>
<h2 id="读写缓存-amp-解析数据"><a href="#读写缓存-amp-解析数据" class="headerlink" title="读写缓存&amp;解析数据"></a>读写缓存&amp;解析数据</h2><blockquote>
<p>在访问网路的基类<code>BaseProtocol.java</code>中读写缓存</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 写缓存</span></div><div class="line"><span class="comment">// 以url为key, 以json为value</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCache</span><span class="params">(<span class="keyword">int</span> index, String json)</span> </span>&#123;</div><div class="line">    <span class="comment">// 以url为文件名, 以json为文件内容,保存在本地</span></div><div class="line">    File cacheDir = UIUtils.getContext().getCacheDir();<span class="comment">// 本应用的缓存文件夹</span></div><div class="line">    <span class="comment">// 生成缓存文件</span></div><div class="line">    File cacheFile = <span class="keyword">new</span> File(cacheDir, getKey() + <span class="string">"?index="</span> + index</div><div class="line">            + getParams());</div><div class="line">    FileWriter writer = <span class="keyword">null</span>;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        writer = <span class="keyword">new</span> FileWriter(cacheFile);</div><div class="line">        <span class="comment">// 缓存失效的截止时间</span></div><div class="line">        <span class="keyword">long</span> deadline = System.currentTimeMillis() + <span class="number">30</span> * <span class="number">60</span> * <span class="number">1000</span>;<span class="comment">// 半个小时有效期</span></div><div class="line">        writer.write(deadline + <span class="string">"\n"</span>);<span class="comment">// 在第一行写入缓存时间, 换行</span></div><div class="line">        writer.write(json);<span class="comment">// 写入json</span></div><div class="line">        writer.flush();</div><div class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">        e.printStackTrace();</div><div class="line">    &#125; <span class="keyword">finally</span> &#123;</div><div class="line">        IOUtils.close(writer);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">// 读缓存</span></div><div class="line"><span class="function"><span class="keyword">public</span> String <span class="title">getCache</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</div><div class="line">    <span class="comment">// 以url为文件名, 以json为文件内容,保存在本地</span></div><div class="line">    File cacheDir = UIUtils.getContext().getCacheDir();<span class="comment">// 本应用的缓存文件夹</span></div><div class="line">    <span class="comment">// 生成缓存文件</span></div><div class="line">    File cacheFile = <span class="keyword">new</span> File(cacheDir, getKey() + <span class="string">"?index="</span> + index</div><div class="line">            + getParams());</div><div class="line">    <span class="comment">// 判断缓存是否存在</span></div><div class="line">    <span class="keyword">if</span> (cacheFile.exists()) &#123;</div><div class="line">        <span class="comment">// 判断缓存是否有效</span></div><div class="line">        BufferedReader reader = <span class="keyword">null</span>;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            reader = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> FileReader(cacheFile));</div><div class="line">            String deadline = reader.readLine();<span class="comment">// 读取第一行的有效期</span></div><div class="line">            <span class="keyword">long</span> deadtime = Long.parseLong(deadline);</div><div class="line">            <span class="keyword">if</span> (System.currentTimeMillis() &lt; deadtime) &#123;<span class="comment">// 当前时间小于截止时间,</span></div><div class="line">                <span class="comment">// 说明缓存有效</span></div><div class="line">                <span class="comment">// 缓存有效</span></div><div class="line">                StringBuffer sb = <span class="keyword">new</span> StringBuffer();</div><div class="line">                String line;</div><div class="line">                <span class="keyword">while</span> ((line = reader.readLine()) != <span class="keyword">null</span>) &#123;</div><div class="line">                    sb.append(line);</div><div class="line">                &#125;</div><div class="line">                <span class="keyword">return</span> sb.toString();</div><div class="line">            &#125;</div><div class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125; <span class="keyword">finally</span> &#123;</div><div class="line">            IOUtils.close(reader);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line">&#125;</div><div class="line"><span class="comment">// 解析json数据, 子类必须实现</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> T <span class="title">parseData</span><span class="params">(String result)</span></span>;</div></pre></td></tr></table></figure>
<blockquote>
<p>解析首页数据</p>
<p>protocol —&gt; <code>HomeProtocol.java</code></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> ArrayList&lt;AppInfo&gt; <span class="title">parseData</span><span class="params">(String result)</span> </span>&#123;</div><div class="line">    <span class="comment">// Gson, JsonObject</span></div><div class="line">    <span class="comment">// 使用JsonObject解析方式: 如果遇到&#123;&#125;,就是JsonObject;如果遇到[], 就是JsonArray</span></div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        JSONObject jo = <span class="keyword">new</span> JSONObject(result);</div><div class="line">        <span class="comment">// 解析应用列表数据</span></div><div class="line">        JSONArray ja = jo.getJSONArray(<span class="string">"list"</span>);</div><div class="line">        ArrayList&lt;AppInfo&gt; appInfoList = <span class="keyword">new</span> ArrayList&lt;AppInfo&gt;();</div><div class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; ja.length(); i++) &#123;</div><div class="line">            JSONObject jo1 = ja.getJSONObject(i);</div><div class="line">            AppInfo info = <span class="keyword">new</span> AppInfo();</div><div class="line">            info.des = jo1.getString(<span class="string">"des"</span>);</div><div class="line">            info.downloadUrl = jo1.getString(<span class="string">"downloadUrl"</span>);</div><div class="line">            info.iconUrl = jo1.getString(<span class="string">"iconUrl"</span>);</div><div class="line">            info.id = jo1.getString(<span class="string">"id"</span>);</div><div class="line">            info.name = jo1.getString(<span class="string">"name"</span>);</div><div class="line">            info.packageName = jo1.getString(<span class="string">"packageName"</span>);</div><div class="line">            info.size = jo1.getLong(<span class="string">"size"</span>);</div><div class="line">            info.stars = (<span class="keyword">float</span>) jo1.getDouble(<span class="string">"stars"</span>);</div><div class="line">            appInfoList.add(info);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 初始化轮播条的数据</span></div><div class="line">        JSONArray ja1 = jo.getJSONArray(<span class="string">"picture"</span>);</div><div class="line">        ArrayList&lt;String&gt; pictures = <span class="keyword">new</span> ArrayList&lt;String&gt;();</div><div class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; ja1.length(); i++) &#123;</div><div class="line">            String pic = ja1.getString(i);</div><div class="line">            pictures.add(pic);</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> appInfoList;</div><div class="line">    &#125; <span class="keyword">catch</span> (JSONException e) &#123;</div><div class="line">        e.printStackTrace();</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<h2 id="加载首页数据-amp-实现分页加载"><a href="#加载首页数据-amp-实现分页加载" class="headerlink" title="加载首页数据&amp;实现分页加载"></a>加载首页数据&amp;实现分页加载</h2><blockquote>
<p>经过上面的封装，我们已经拿到了，网络访问请求到的数据，也实现了一定的加载逻辑，</p>
<p>现在需要在特定的页面加载指定的数据</p>
<p>我们需要将之前封装ListView测试的数据泛型更改为<code>&lt;AppInfo&gt;</code></p>
</blockquote>
<ul>
<li>在<code>HomeFragment.java</code>加载首页数据解析<code>HomeProtocol.java</code></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> ResultState <span class="title">onLoad</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="comment">// 请求网络, HttpClient, HttpUrlConnection, XUtils</span></div><div class="line">    <span class="comment">// data = new ArrayList&lt;String&gt;();</span></div><div class="line">    <span class="comment">// for (int i = 0; i &lt; 20; i++) &#123;</span></div><div class="line">    <span class="comment">// data.add("测试数据:" + i);</span></div><div class="line">    <span class="comment">// &#125;</span></div><div class="line">    HomeProtocol protocol = <span class="keyword">new</span> HomeProtocol();</div><div class="line">    data = protocol.getData(<span class="number">0</span>);<span class="comment">// 加载第一页数据</span></div><div class="line">    <span class="keyword">return</span> check(data);<span class="comment">// 校验数据并返回</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>由于在<code>BaseProtocol.java</code>中采用分页加载数据，所以在<code>HomeFragment.java</code>中实现分页加载</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> ArrayList&lt;AppInfo&gt; <span class="title">onLoadMore</span><span class="params">()</span> </span>&#123;</div><div class="line">    HomeProtocol protocol = <span class="keyword">new</span> HomeProtocol();</div><div class="line">    <span class="comment">// 20, 40, 60....</span></div><div class="line">    <span class="comment">// 下一页数据的位置 等于 当前集合大小</span></div><div class="line">    ArrayList&lt;AppInfo&gt; moreData = protocol.getData(getListSize());</div><div class="line">    SystemClock.sleep(<span class="number">2000</span>);</div><div class="line">    <span class="keyword">return</span> moreData;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<h2 id="首页加载data-name实现效果"><a href="#首页加载data-name实现效果" class="headerlink" title="首页加载data.name实现效果"></a>首页加载<code>data.name</code>实现效果</h2><p><img src="http://oce2u4egr.bkt.clouddn.com/ApplicationMarket-Protocol.gif"></p>
</blockquote>
<h2 id="😘😘😘，"><a href="#😘😘😘，" class="headerlink" title="😘😘😘，"></a>😘😘😘，</h2><p>不管前面的页面框架搭建，还是后面的ListView和网络访问解析的封装，</p>
<p>在逻辑上都会有很晦涩，难以理解的地方</p>
<p>但是，这也预示了我们后面的页面填充就会很方便，这也是框架搭建的方便之处……</p>
<blockquote>
<p>源码地址: <a href="https://github.com/LeoStones/ApplicationMarket/tree/master/ApplicationMarket" target="_blank" rel="external">ApplicationMarket</a></p>
<p>感谢关注，欢迎Star💚</p>
</blockquote>

      
    </div>


    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag">#Android</a>
          
            <a href="/tags/Project/" rel="tag">#Project</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/coding/android/project/ApplicationMarket/应用市场(一)-前期准备和页面框架搭建/" rel="next" title="应用市场（一）——前期准备和页面框架搭建">
                <i class="fa fa-chevron-left"></i> 应用市场（一）——前期准备和页面框架搭建
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/coding/android/project/ApplicationMarket/应用市场(三)-页面数据填充/" rel="prev" title="应用市场（三）——页面数据填充">
                应用市场（三）——页面数据填充 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="hypercomments_widget"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
      
        
          <ul class="sidebar-nav motion-element">
            <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
              Table of Contents
            </li>
            <li class="sidebar-nav-overview" data-target="site-overview">
              Overview
            </li>
          </ul>
        
      



      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="睡沙发的沙皮狗" />
          <p class="site-author-name" itemprop="name">睡沙发的沙皮狗</p>
           
              <p class="site-description motion-element" itemprop="description">睡沙发的沙皮狗 Leeifme</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">17</span>
                <span class="site-state-item-name">posts</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">categories</span>
              
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">tags</span>
              
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/leeifme" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/5406937103/profile?topnav=1&wvr=6" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        

        


      </section>
      
        
        <!--noindex-->
          <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
            <div class="post-toc">

              
                
              

              
                <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言:</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#封装ListView"><span class="nav-number"></span> <span class="nav-text">封装ListView</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#第一层封装"><span class="nav-number">1.</span> <span class="nav-text">第一层封装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#第二层封装"><span class="nav-number">2.</span> <span class="nav-text">第二层封装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ListView增加加载更多布局"><span class="nav-number">3.</span> <span class="nav-text">ListView增加加载更多布局</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#封装ListView加载测试数据，演示效果"><span class="nav-number"></span> <span class="nav-text">封装ListView加载测试数据，演示效果</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#网络数据请求封装"><span class="nav-number"></span> <span class="nav-text">网络数据请求封装</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#导入http工具包及工具类"><span class="nav-number">1.</span> <span class="nav-text">导入http工具包及工具类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#封装访问网络的基类"><span class="nav-number">2.</span> <span class="nav-text">封装访问网络的基类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#读写缓存-amp-解析数据"><span class="nav-number">3.</span> <span class="nav-text">读写缓存&解析数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#加载首页数据-amp-实现分页加载"><span class="nav-number">4.</span> <span class="nav-text">加载首页数据&实现分页加载</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#首页加载data-name实现效果"><span class="nav-number">5.</span> <span class="nav-text">首页加载data.name实现效果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#😘😘😘，"><span class="nav-number">6.</span> <span class="nav-text">😘😘😘，</span></a></li></ol></div>
              

            </div>
          </section>
        <!--/noindex-->
        
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">睡沙发的沙皮狗</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/zproo/hexo-blog">
    Next
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span></span>
  

  
    <span class="site-pv"><i class="fa fa-eye"> </i><span class="busuanzi-value" id="busuanzi_value_site_pv"></span></span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  





	

		<script type="text/javascript">
		_hcwp = window._hcwp || [];

		_hcwp.push({widget:"Bloggerstream", widget_id: 92841, selector:".hc-comment-count", label: "{\%COUNT%\}" });

		
		_hcwp.push({widget:"Stream", widget_id: 92841, xid: "coding/android/project/ApplicationMarket/应用市场(二)-基础封装/"});
		

		(function() {
		if("HC_LOAD_INIT" in window)return;
		HC_LOAD_INIT = true;
		var lang = (navigator.language || navigator.systemLanguage || navigator.userLanguage || "en").substr(0, 2).toLowerCase();
		var hcc = document.createElement("script"); hcc.type = "text/javascript"; hcc.async = true;
		hcc.src = ("https:" == document.location.protocol ? "https" : "http")+"://w.hypercomments.com/widget/hc/92841/"+lang+"/widget.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hcc, s.nextSibling);
		})();
		</script>

	







  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').fadeToggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ decodeURIComponent(data_url) +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').fadeOut(function() {
          $(".popoverlay").remove();
          $('body').css('overflow', '');
      });
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("6mFxqINb4RcjTGhNbtCzfWI1-gzGzoHsz", "c4qK91bIu9qFdGeimnKdriiK");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


</body>
</html>
